/*
 * @Author: yangzonglong
 * @Date: 2020-04-08 10:56:04
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-05-25 08:55:26
 * @Auditor: 
 */
import history from './../../app/history';
import { PACKAGE_NAME } from './../../app/automatic/package';
import routes from './../../app/automatic/routes';

let permitMap: any = {};

const defaultRoutePermitInPath = {
  create: true,
  edit: true,
  view: true,
  download: true,
  upload: true,
  delete: true
}

export type CompanyFunctionRoleProps = {
  create: boolean,
  edit: boolean,
  view: boolean,
  download: boolean,
  upload: boolean,
  delete: boolean
}

type ChildItemProps = {
  functionUrl: string,
  CompanyFunctionRole: CompanyFunctionRoleProps
}

type MenuItemProps = {
  functionGroupDesc: string,
  children: ChildItemProps[]
}

type MenuProps = {
  name: string,
  moduleCode: string,
  menu: MenuItemProps[]
}

const getCompletePath = (pathname: string) => `/${PACKAGE_NAME}${pathname}`;

export function getAuthPath() {
  const pathname = history.location.pathname,
        completePath = getCompletePath(pathname);

  if (permitMap[completePath]) return completePath;

  let flag = true, curRoute = routes.find(item => item.path === pathname); // 当前路由配置

  while (flag) {
    const cur = routes.find(item => item.path === curRoute?.parentPath);

    if (!cur) {
      flag = false; // 停止
    } else {
      curRoute = cur;
      if (permitMap[getCompletePath(cur.path)]) {
        flag = false
      }
    }
  }
  
  return curRoute?.path ? getCompletePath(curRoute.path) : completePath
}

export default () => {
  if (!Object.keys(permitMap).length) initRoutePermit(PACKAGE_NAME);

  const pathname = getAuthPath();
  return permitMap[pathname] || defaultRoutePermitInPath;
}

function initRoutePermit(appId: string) {
  const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
  const currentAppMenu = filterCurrentAppMenu(userInfo.menuList || [], appId);

  currentAppMenu.forEach(group => {
    group.children.forEach(menu => {
      const companyFunctionRole = menu.CompanyFunctionRole || {};
      const functionUrl = '/' + menu.functionUrl.replace('.', '/');
      permitMap[functionUrl] = companyFunctionRole;
    })
  })
}

function filterCurrentAppMenu(menu: MenuProps[], appId: string) {
  return menu.filter(item => item.moduleCode === appId)[0]?.menu || []
}